const audio = require("../models/audio")
const fs = require('fs')

var express = require('express');
var router = express.Router();

const path = require('path')

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            console.log('eee')
            // console.log('eee',fields.audio)
            let today = new Date(fields.today).toLocaleDateString()
            let dir_path = `${ path.resolve(__dirname, '../../static/audio') }\/${ today }`
            let filename = fields.filename,
                file_path = `${dir_path}\/${filename}`
                filename_path = `${dir_path}\/${filename}.txt`
            // let chunk_dir = `${file_path}\/${fields.filename}.txt`

            let pathList = fs.readdirSync(file_path)
            if(pathList.length<fields.total){
              res.json({ 'state': false, 'msg': '切片缺失' })
              return
            }

            fs.writeFileSync(filename_path, '')
            pathList.sort((a, b) =>  a.localeCompare(b)).forEach(item => {
              fs.appendFileSync(filename_path, fs.readFileSync(`${file_path}\/${item}`))
              fs.unlinkSync(`${file_path}\/${item}`)
            })
            let times_count = 0
            await new Promise(resolve => {
              const intervalObj = setInterval(() => {
                let _pathList = fs.readdirSync(file_path)
                if(_pathList.length===0){
                  fs.rmdirSync(file_path);
                  times_count++;
                  clearInterval(intervalObj); 
                  resolve();
                } else if(times_count>10){
                  res.json({ 'state': false, 'msg': '无法删除切片' })
                  clearInterval(intervalObj); 
                  resolve();
                }
              }, 100);
            })
            
            await audio.create({
              date: today,
              filename: fields.filename,
              total: fields.total,
              UUID: fields.UUID,
              path: filename_path,
              pointId: fields.pointId,
              demoId: fields.demoId,
              ideaId: fields.ideaId
            })
            res.json({ 'state': true, 'msg': '合并切片成功' })
       
            // let today_file = await audio.find({
            //     date: today
            // })
            // let audio_doc = null
            // if(today_file.length===0){
            //     audio_doc = await audio.create({
            //         date: today,
            //         index: 1,
            //         UUID: fields.UUID,
            //         audio: `${ path.resolve(__dirname, '../../static/audio') }\/${ today }\/1.txt`,
            //         pointId: fields.pointId,
            //         demoId: fields.demoId,
            //         ideaId: fields.ideaId
            //     })
            // } else {
            //     let index = today_file[today_file.length-1].index + 1
            //     audio_doc = await audio.create({
            //         date: today,
            //         index: index,
            //         UUID: fields.UUID,
            //         audio: `${ path.resolve(__dirname, '../../static/audio') }\/${ today }\/${ index }.txt`,
            //         pointId: fields.pointId,
            //         demoId: fields.demoId,
            //         ideaId: fields.ideaId
            //     })
            // }
            // let dir_exist = await directory_exist(today)
            // if(!dir_exist){
            //     await directory_create(today)
            // }
            // console.log(audio_doc)
            // var write_file = function(Path, Data) {
            //     return new Promise((resolve, reject) => {
            //         fs.writeFile(Path, Data, function(error) {
            //             // console.log('文件写入成功')
            //             if(error) {
            //                 console.log(error)
            //                 resolve({ 'state': true, 'msg': '生成文件失败' });
            //             } else {
            //               console.log('写入成功')
            //               resolve({ 'state': true, 'msg': '生成文件成功' });
            //             }
            //         })
            //     })
            // }
            // let returndata = await write_file(audio_doc.audio, fields.audio)
            // res.json(returndata)
            
        }

    });

});

module.exports = router;